package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.stark.ve.core.SpeedMode;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.AlbumAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.ActivitySelVideoBinding;
import flc.ast.databinding.ActivityVideoSpeedBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRecycleView;

public class VideoSpeedActivity extends BaseAc<ActivityVideoSpeedBinding> {

    public static String videoPath = "";
    private long videoLength = 0;
    private float currentSpeed = 1.0f;//视频速度
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
            }
            mHandler.postDelayed(mTaskUpdateTime, 500);
        }
    };
    private List<String> listSel = new ArrayList<>();
    private AlbumAdapter albumAdapter;
    private Dialog mySelAlbumDialog;
    private Dialog myAddAlbumDialog;
    private EditText dialogAdd;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_speed;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoSpeedBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvVideoSpeed1.setOnClickListener(this);
        mDataBinding.tvVideoSpeed2.setOnClickListener(this);
        mDataBinding.tvVideoSpeed3.setOnClickListener(this);
        mDataBinding.tvVideoSpeed4.setOnClickListener(this);
        mDataBinding.tvVideoSpeed5.setOnClickListener(this);
        mDataBinding.ivVideoSpeedSave.setOnClickListener(this);

        mHandler = new Handler();
        mDataBinding.tvDuration.setText("00:00" + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
                mDataBinding.ivPlay.setSelected(false);
                mp.seekTo(1);
                stopTime();
            }
        });

        albumAdapter = new AlbumAdapter();
        albumAdapter.setEdit(true);
        albumAdapter.setOnItemClickListener(this);

        //选择相册弹框
        selAlbumDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlay.setSelected(false);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlay.setSelected(true);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvVideoSpeed1:
                clearSelect();
                mDataBinding.tvVideoSpeed1.setBackgroundResource(R.drawable.speed_sel);
                mDataBinding.tvVideoSpeed1.setTextColor(Color.parseColor("#1E1E1E"));
                serSpeed(0.5f);
                break;
            case R.id.tvVideoSpeed2:
                clearSelect();
                mDataBinding.tvVideoSpeed2.setBackgroundResource(R.drawable.speed_sel);
                mDataBinding.tvVideoSpeed2.setTextColor(Color.parseColor("#1E1E1E"));
                serSpeed(0.75f);
                break;
            case R.id.tvVideoSpeed3:
                clearSelect();
                mDataBinding.tvVideoSpeed3.setBackgroundResource(R.drawable.speed_sel);
                mDataBinding.tvVideoSpeed3.setTextColor(Color.parseColor("#1E1E1E"));
                serSpeed(1.0f);
                break;
            case R.id.tvVideoSpeed4:
                clearSelect();
                mDataBinding.tvVideoSpeed4.setBackgroundResource(R.drawable.speed_sel);
                mDataBinding.tvVideoSpeed4.setTextColor(Color.parseColor("#1E1E1E"));
                serSpeed(1.5f);
                break;
            case R.id.tvVideoSpeed5:
                clearSelect();
                mDataBinding.tvVideoSpeed5.setBackgroundResource(R.drawable.speed_sel);
                mDataBinding.tvVideoSpeed5.setTextColor(Color.parseColor("#1E1E1E"));
                serSpeed(2.0f);
                break;
            case R.id.ivVideoSpeedSave://保存
                getAlbumData();
                mySelAlbumDialog.show();
                break;
            //选择相册弹框
            case R.id.tvDialogSelAlbumCancel://取消
                mySelAlbumDialog.dismiss();
                break;
            case R.id.tvDialogSelAlbumConfirm://确定
                if (listSel.size() == 0) return;
                saveVideo(videoPath);
                break;
            //新建相册弹框
            case R.id.ivDialogAddAlbumConfirm://确定
                addAlbum();
                break;
            case R.id.ivDialogAddAlbumCancel://取消
                myAddAlbumDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (position == 0) {
            //新建相册弹框
            addAlbumDialog();
            myAddAlbumDialog.show();
            return;
        }
        if (albumAdapter.getItem(position).isSelected()) {
            albumAdapter.getItem(position).setSelected(false);
            listSel.remove(albumAdapter.getItem(position).getId());
        } else {
            albumAdapter.getItem(position).setSelected(true);
            listSel.add(albumAdapter.getItem(position).getId());
        }
        albumAdapter.notifyItemChanged(position);
    }

    @Override
    protected void initData() {

    }

    //保存视频
    private void saveVideo(String videoPath) {
        EditorHolder.editor().videoChangeSpeed(videoPath, currentSpeed, SpeedMode.ALL, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到本地
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                        List<MyAlbumBean> listSp = AppSpUtils.getVideoAlbumList();
                        if (listSp != null && listSp.size() > 0) {
                            for (MyAlbumBean bean : listSp) {
                                for (String s : listSel) {
                                    if (bean.getId().equals(s)) {
                                        List<String> listSave = new ArrayList<>();
                                        listSave.add(outFilePath);
                                        if (bean.getListData() != null && bean.getListData().size() > 0) {
                                            bean.getListData().addAll(listSave);
                                        } else {
                                            bean.setListData(listSave);
                                        }
                                        break;
                                    }
                                }
                            }
                            AppSpUtils.saveVideoAlbumList(listSp);
                        }
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                        startActivity(HomeActivity.class);
                    }

                    @Override
                    public void accept(String obj) {

                    }
                });
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_def));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.save_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //设置速度
    private void serSpeed(float speed) {
        currentSpeed = speed;
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                PlaybackParams playbackParams = mediaPlayer.getPlaybackParams();
                playbackParams.setSpeed(currentSpeed);
                mediaPlayer.setPlaybackParams(playbackParams);
                mDataBinding.ivPlay.setSelected(true);
                startTime();
            }
        });
    }

    private void getAlbumData() {
        List<MyAlbumBean> listSp = AppSpUtils.getVideoAlbumList();
        if (listSp == null) {
            listSp = new ArrayList<>();
        }
        listSp.add(0, new MyAlbumBean());
        if (listSp != null && listSp.size() > 0) {
            albumAdapter.setList(listSp);
        }
    }

    private void addAlbum() {
        String albumName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myAddAlbumDialog.dismiss();
        //准备数据
        List<MyAlbumBean> listSave = new ArrayList<>();
        listSave.add(new MyAlbumBean(TimeUtils.getNowString(), albumName, "", new ArrayList<>(), false));
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getVideoAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveVideoAlbumList(listSp);
        } else {
            AppSpUtils.saveVideoAlbumList(listSave);
        }
        getAlbumData();
    }

    //选择相册弹框
    private void selAlbumDialog() {
        mySelAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_album, null);
        mySelAlbumDialog.setContentView(inflate);
        mySelAlbumDialog.setCancelable(true);
        Window dialogWindow = mySelAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogSelAlbumConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogSelAlbumCancel);
        StkRecycleView recycleView = inflate.findViewById(R.id.rvAlbumList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        recycleView.setAdapter(albumAdapter);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //新建相册弹框
    private void addAlbumDialog() {
        myAddAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddAlbumDialog.setContentView(inflate);
        myAddAlbumDialog.setCancelable(true);
        Window dialogWindow = myAddAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView right = inflate.findViewById(R.id.ivDialogAddAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddAlbumCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddAlbumText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTime();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mDataBinding.ivPlay.setSelected(true);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.start();
        startTime();
    }

    private void clearSelect() {
        mDataBinding.tvVideoSpeed1.setBackgroundResource(R.drawable.speed_bg);
        mDataBinding.tvVideoSpeed1.setTextColor(Color.parseColor("#991E1E1E"));
        mDataBinding.tvVideoSpeed2.setBackgroundResource(R.drawable.speed_bg);
        mDataBinding.tvVideoSpeed2.setTextColor(Color.parseColor("#991E1E1E"));
        mDataBinding.tvVideoSpeed3.setBackgroundResource(R.drawable.speed_bg);
        mDataBinding.tvVideoSpeed3.setTextColor(Color.parseColor("#991E1E1E"));
        mDataBinding.tvVideoSpeed4.setBackgroundResource(R.drawable.speed_bg);
        mDataBinding.tvVideoSpeed4.setTextColor(Color.parseColor("#991E1E1E"));
        mDataBinding.tvVideoSpeed5.setBackgroundResource(R.drawable.speed_bg);
        mDataBinding.tvVideoSpeed5.setTextColor(Color.parseColor("#991E1E1E"));
    }

}